<?php
/**
 * @name        Simple Photo Gallery
 * @version	1.0: album.php
 * @since       Joomla 1.5
 * @subpackage	com_simplephotogallery
 * @author      Apptha
 * @copyright   Copyright (C) 2011 Powered by Apptha
 * @license     GNU/GPL http://www.gnu.org/copyleft/gpl.html
 * @abstract    Album model for listing and create new albums.
 */
/* no direct access*/
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.application.component.model' );
global $mainframe;

$mainframe = JFactory::getApplication();

class SimplephotogalleryModelalbum extends JModel
{
	//Function to get album list from album table. 
	function getAlbum()
    {
		global $option, $mainframe;
        $mainframe = JFactory::getApplication();
        $filter_order = $mainframe->getUserStateFromRequest( $option.'filter_order', 'filter_order', 'album_name', 'cmd' );
        $filter_order_Dir = $mainframe->getUserStateFromRequest( $option.'filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );
        $filter_id = $mainframe->getUserStateFromRequest( $option.'filter_id',		'filter_id',		'',			'int' );

    	if ($filter_order != "id" && $filter_order != "album_name" && $filter_order != "published") 
    		{
	            $filter_order = "id";
	            $filter_order_Dir = "asc";
        	}
        
        // search filter
        $search = $mainframe->getUserStateFromRequest( $option.'search','search','','string' );
        
        // page navigation
        $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
        
        $limitstart = $mainframe->getUserStateFromRequest('global.list.limitstart', 'limitstart', 0, 'int');
        
        $db =& JFactory::getDBO();

        $query = "SELECT count(*) FROM #__simplephotogallery_album";
        $db->setQuery( $query);
        $total = $db->loadResult();
        
        jimport('joomla.html.pagination');

        $pageNav = new JPagination($total, $limitstart, $limit);

        $lists['order_Dir']	= $filter_order_Dir;
        $lists['order']		= $filter_order;

        if($filter_order) 
        {
            //sorting order
            $query = "SELECT * FROM #__simplephotogallery_album ";
            if(isset($lists["order_Dir"]) && isset($lists["order"]) && $lists["order"] !="ordering" ){
                
                $query .= " ORDER BY  ".$lists["order"]." ".$lists["order_Dir"];
            }
            $query .= " LIMIT ".$pageNav->limitstart.",".$pageNav->limit;
            
            $db->setQuery( $query );
            $rows = $db->loadObjectList();
        }
        if (trim($search) !="" ) 
        {
            //sorting order
            $query ="SELECT * FROM #__simplephotogallery_album where album_name LIKE '%$search%'";

            if(isset($lists["order_Dir"]) && isset($lists["order"]) && $lists["order"] !="ordering" ){
                $query .= " ORDER BY  ".$lists["order"]." ".$lists["order_Dir"];
            }           
            $db->setQuery($query);
            $rows = $db->loadObjectList();
        }
        if ($db->getErrorNum()) 
        {
            echo $db->stderr();
            return false;
        }
        
        $album = array('pageNav' => $pageNav,'limitstart'=>$limitstart,'lists'=>$lists,'option'=>$option,'row'=>$rows);
        
        return $album;
    }
    
    //Function to save album to the database. 
	function saveAlbum($album)
	{
		if(!JRequest::getVar('alias_name'))
		{
			$aliasName = JRequest::getVar('album_name');
		//$al = $_REQUEST['alias_name'];
		$aliasName = strtolower(trim($aliasName));
		$aliasName = str_replace(' ','-',$aliasName);
		}
		else 
		{
		$aliasName = JRequest::getVar('alias_name');
		//$al = $_REQUEST['alias_name'];
		$aliasName = strtolower(trim($aliasName));
		$aliasName = str_replace(' ','-',$aliasName);
		}
		$db = JFactory::getDBO();
		if(JRequest::getVar('id'))
		{
			$albumId = JRequest::getVar('id');
			$query = "SELECT id FROM #__simplephotogallery_album where id != ".$albumId." AND alias_name = '".$aliasName."'";
		}
		else
		{
			$query = "SELECT id FROM #__simplephotogallery_album where alias_name = '".$aliasName."'";
		}
        $db->setQuery( $query);
        $total = $db->loadResult();
		if(!empty($total))
        {
        	$aliasName = $aliasName.'-'.time();
        }
        
	$albumTableRow =& $this->getTable('album');

        if (!$albumTableRow->bind($album)) 
        {
            JError::raiseError(500, 'Error binding data');
        }
        
        $albumTableRow->alias_name = $aliasName;
        if (!$albumTableRow->check()) 
        {
            JError::raiseError(500, 'Invalid data');
        }
        if (!$albumTableRow->store()) 
        {
            $errorMessage = $albumTableRow->getError();
            JError::raiseError(500, 'Error binding data: '.$errorMessage);
        }
	}
	
	//Function to get album from the table based on album id.
	function getAlbums($id)
    {
        global $option;
        $row =& JTable::getInstance('album', 'Table');
        $cid = JRequest::getVar( 'cid', array(0), '', 'array' );
        $id = $cid[0];
        $key = $row->load($id);
        $lists['published'] = JHTML::_('select.booleanlist', 'published','class="inputbox"', $row->published);
        $album = array('option'=>$option,'row'=>$row,'lists'=>$lists);
        return $album;
    }
    
    //Function to publish or unpublish the album from the list.
	function publish($arrayIDs)
    {
        echo $arrayIDs['task'];
        if($arrayIDs['task']=="publish")
        {
            $publish = 1;
        }
        else
        {
            $publish = 0;
        }
        $n = count($arrayIDs['cid']);
        for($i = 0; $i < $n; $i++)
        {
            $query = "UPDATE #__simplephotogallery_album set published=".$publish." WHERE id=".$arrayIDs['cid'][$i];
            $db = $this->getDBO();
            $db->setQuery($query);
            $db->query();
        }
    }
    
    //Function to delete the album from the list.
 	function deleteAlbum($arrayIDs)
    {
        $db = $this->getDBO();

        $query = "DELETE FROM #__simplephotogallery_album WHERE id IN (".implode(',', $arrayIDs).")"; //to replace #_ with #_
        $db->setQuery($query);
        $db->query();

        $query = "SELECT count(*) FROM #__simplephotogallery_album";
        $db->setQuery( $query);
        $total = $db->loadResult();
    }
}